package logic

import (
	"context"
	// "fmt"

	"demo/internal/errorx"
	"demo/internal/svc"
	"demo/internal/types"
	"demo/model"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

const (
	Choice = iota + 1
	Description 
)

const (
	True = iota
	False
)

type QuestionCreateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	modelS model.ServeyModel
	modelQ model.QuestionModel
	modelO model.OptionModel
}

func NewQuestionCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QuestionCreateLogic {
	return &QuestionCreateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		modelS: model.NewServeyModel(svcCtx.Orm,svcCtx.Config.Cache),
		modelQ: model.NewQuestionModel(svcCtx.Orm),
		modelO: model.NewOptionModel(svcCtx.Orm),
	}
}

func (l *QuestionCreateLogic) QuestionCreate(req *types.QuestionCreateRequest) (resp *types.StandredIdResponse, err error) {
	// todo: add your logic here and delete this line
	var questionId int64
	// step1 检查servey、父节点ID以及父节点是否存在
	err = l.modelS.Trans(l.ctx,func(context context.Context, session sqlx.Session) error {
		servey,_ := l.modelS.FindOne(l.ctx,session,req.ServeyId)
		if servey == nil {
			return errorx.NewBizError(500,"问卷内容为空")
		}
		if req.QstSort != -1 {
			qst,_ := l.modelQ.FindOne(l.ctx,session,req.QstSort)
			if qst == nil {
				return errorx.NewBizError(500,"查询不到父节点")
			}
		}
		qst1,err := l.modelQ.FindOneByQstSort(l.ctx,session,req.QstSort)
		if err != sqlx.ErrNotFound && qst1.ServeyId == servey.Id {
			return errorx.NewBizError(500,"父节点已存在子节点")
		}
		question := &model.Question{
			ServeyId: req.ServeyId,
			QstContent: req.QstContent,
			Type: req.Type,
			QstSort: req.QstSort,
			IsMustAnswer: req.IsMustAnswer,
			IsShow: req.IsShow,
		}
		questionId,err = l.modelQ.InsertGetId(context,session,question)
		if err != nil {
			return errorx.NewBizError(500,"问题插入失败")
		}
		// step2 检查问题的类型 ～ 如果是选择题需要插入数据到选择题表
		if req.Type == Choice && len(req.Options) > 0 {
			options := make([]*model.Option,0)
			for _,val := range req.Options {
				option := &model.Option{
					ServeyId: req.ServeyId,
					QuestionId: questionId,
					OpContent: val.OpContent,
					IsTrue: val.IsTrue,
				}
				options = append(options, option)
			}
			l.modelO.BulkInsert(context,session,options)
		}
		return nil
	})
	if err != nil {
		return nil,err
	}

	return &types.StandredIdResponse{
		Code: 200,
		Msg: "问题添加成功",
		Data: types.IdRequest{
			Id: questionId,
		},
	},nil
}
